import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { FormattedMessage, injectIntl } from 'react-intl';
import {actions} from "mirrorx";
import {Table, Checkbox, Button, Modal, Message,Radio,FormControl,Pagination } from "tinper-bee";
import moment from 'moment'
import DatePicker from "bee-datepicker";
import FormError from 'components/FormError';
import Grid from 'components/Grid';
import SearchPanel from 'components/SearchPanel';
import RefComponent from 'components/RefComponent';
import FormList from 'components/FormList';
import multiSelect from "bee-table/build/lib/multiSelect.js";
import {deepClone,getValidateFieldsTrim,initValueString,renderEnable} from "utils";

const MultiSelectTable = multiSelect(Table,Checkbox)
let {RangePicker} = DatePicker;

import './index.less'
import { Children } from 'react';

const FormItem = FormList.Item;

const columns1 = [
    { title: "启用状态", dataIndex: "isEnable", key: "isEnable", width: 100, render: (text) => {
        return renderEnable(text);
    } },
    { title: "活动名称", dataIndex: "activityName", key: "activityName", width: 100 },
    { title: "组织", dataIndex: "organizationName", key: "organizationName" },
    { title: "计划销售额", dataIndex: "planSaleAmount", key: "planSaleAmount", width: 100},
    { title: "计划报销额", dataIndex: "planCostAmount", key: "planCostAmount", width: 100},
    { title: "实际销售额", dataIndex: "actualSaleAmount", key: "actualSaleAmount", width: 100},
    { title: "理论费用额", dataIndex: "theoreticalCostAmount", key: "theoreticalCostAmount", width: 100},
    { title: "确认金额", dataIndex: "confirmationAmount", key: "confirmationAmount", width: 100},
    { title: "报销金额", dataIndex:"reimbursementAmount",key: "reimbursementAmount", width: 100}
  ];

const columns1Child = [
    { title: "活动开始日期", dataIndex: "activityStartDate", key: "activityStartDate", width: 100},
    { title: "活动结束日期", dataIndex: "activityEndDate", key: "activityEndDate", width: 100},
    { title: "渠道", dataIndex: "channelTypeName", key: "channelTypeName", width: 100},
    { title: "客户", dataIndex: "customerName", key: "customerName", width: 100},
    { title: "销售类型", dataIndex: "saleTypeName", key: "saleTypeName", width: 100},
    { title: "计划销售额", dataIndex: "planSaleAmount", key: "planSaleAmount", width: 100},
    { title: "计划报销额", dataIndex: "planCostAmount", key: "planCostAmount", width: 100},
    { title: "计划销售数量", dataIndex: "planSaleNum", key: "planSaleNum", width: 100},
    { title: "计划费用率%", dataIndex: "costRate", key: "costRate", width: 100},
    { title: "单台费用", dataIndex: "singleCost", key: "singleCost", width: 100},
    { title: "实际销售额", dataIndex: "actualSaleAmount", key: "actualSaleAmount", width: 100},
    { title: "理论费用额", dataIndex: "theoreticalCostAmount", key: "theoreticalCostAmount", width: 100},
    { title: "摘要", dataIndex: "brief", key: "brief", width: 100},
    { title: "发生月份", dataIndex: "occurMonth", key: "occurMonth", width: 100},
    { title: "归属年份", dataIndex: "attributionYear", key: "attributionYear", width: 100},
  ];
const searchField1 = [
    // {
    //     enname:"organization",
    //     zhname:"所属组织",
    //     required: false,
    //     refname:"organization",
    //     type:"RefComponent",
    //     realRef:true,
    //     edit: true
    // },
    {
        enname: "billCode",
        zhname: "活动单据号",
        required: false,
        searchType: 'like',
        type: "FormControl",
        edit: true
    },
    {
        enname:"reportArea",
        zhname:"片区",
        required: false,
        realRef:true,
        refname:"marketareas",
        type:"RefComponent",
        edit: true
    },
    {
        enname:"reportPerson",
        zhname:"起案人",
        required: false,
        refname:"personRef",
        realRef:true,
        type:"RefComponent",
        edit: true
    }
]

  const columns2 = [
    { title: "单据类型", dataIndex: "billTypeFeeName", key: "billTypeFeeName", width: 100},
    { title: "活动方案名称", dataIndex: "activityName", key: "activityName", width: 100},
  ];

const columns2Child = [
    { title: "活动开始日期", dataIndex: "activityStartDate", key: "activityStartDate", width: 100},
    { title: "活动结束日期", dataIndex: "activityEndDate", key: "activityEndDate", width: 100},
    { title: "渠道", dataIndex: "channelTypeName", key: "channelTypeName", width: 100},
    { title: "客户", dataIndex: "customerName", key: "customerName", width: 100},
    { title: "销售类型", dataIndex: "saleTypeName", key: "saleTypeName", width: 100},
    { title: "计划销售额", dataIndex: "planSaleAmount", key: "planSaleAmount", width: 100},
    { title: "计划费用额", dataIndex: "planCostAmount", key: "planCostAmount", width: 100},
    { title: "计划销售数量", dataIndex: "planSaleNum", key: "planSaleNum", width: 100},
    { title: "计划费用率%", dataIndex: "costRate", key: "costRate", width: 100},
    { title: "单台费用", dataIndex: "singleCost", key: "singleCost", width: 100},
    { title: "实际销售额", dataIndex: "actualSaleAmount", key: "actualSaleAmount", width: 100},
    { title: "理论费用额", dataIndex: "theoreticalCostAmount", key: "theoreticalCostAmount", width: 100},
    { title: "摘要", dataIndex: "brief", key: "brief", width: 100},
    { title: "发生月份", dataIndex: "occurMonth", key: "occurMonth", width: 100},
    { title: "归属年份", dataIndex: "attributionYear", key: "attributionYear", width: 100},
  ];



  const searchField2 = [
    {
        enname:"organization",
        zhname:"所属组织",
        required: false,
        refname:"organization",
        type:"RefComponent",
        realRef:true,
        edit: true
    },
    {
        enname: "billCode",
        zhname: "活动单据号",
        required: false,
        searchType: 'like',
        type: "FormControl",
        edit: true
    },
    {
        enname:"reportArea",
        zhname:"片区",
        required: false,
        realRef:true,
        refname:"marketareas",
        type:"RefComponent",
        edit: true
    },
    {
        enname:"reportPerson",
        zhname:"起案人",
        required: false,
        refname:"personRef",
        realRef:true,
        type:"RefComponent",
        edit: true
    }
]
class GetDealModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
        }
        sessionStorage.removeItem("childSelectList")
    }

    GetDealModal = (delFlag) => {
        let { selectData,getDealCallback,parentList,openFlag } = this.props;
        let {currentIndex} = this.state;
    
        if (delFlag) {
            let childSelectList = sessionStorage.getItem("childSelectList");
            let SelectData = parentList[currentIndex];
            if(childSelectList && JSON.parse(childSelectList).length == 0) {
                Message.create({ content: "请选择明细", color: 'warning', duration: 10 });
                return;
            }
            parentList = parentList.filter(item=>{
                return item._checked
              })
            if(parentList.length == 0) {
                Message.create({ content: `请选择数据`, color: 'warning', duration: 10 });
                return;
            }
            if(parentList.length > 1) {
                Message.create({ content: `只能选择一条数据！`, color: 'warning', duration: 10 });
                return;
            }
            if(openFlag == "ActivityProgram") {
                SelectData.activityDetails = JSON.parse(childSelectList);
            }else {
                SelectData.confirmSon = JSON.parse(childSelectList);
            }

            let url = "/occ-fee/fee/profit-check/process-convert-from-scheme";
            let param = {
                url: url,
                data:SelectData,
            }
            actions.ProfitCheck.getDeal({param:param,callback:getDealCallback});

        }else {
            this.props.closeGetDealModal();
        }
    }

    search = () => {
        this.props.form.validateFields((err, _values) => {
            let values = getValidateFieldsTrim(_values);
           
            for(let attr in values){
                if(values[attr]===null || values[attr]==="" || (values[attr]&&values[attr].length == 0))
                    delete values[attr];
            }

            this.getQuery(values);
            this.setState({searchForm:values});
        });
    }

    getQuery = (values) => {
        let {openGetDealModal,origalData,openFlag} = this.props;
        values.page = 0;
        values.size = origalData.size;
        let params = {};
        params.param = values;
        let searchField;
        if(openFlag == "ActivityProgram") {
            searchField = searchField1;
        }else {
            searchField = searchField2;
        }
        params.searchField = searchField;
        openGetDealModal(openFlag,params);

    }

    onParentRowClick = (record, index, event) => {
        let {parentList,openFlag} = this.props;
        let currentChildData;
        if(openFlag == "ActivityProgram") {
            currentChildData = parentList[index].activityDetails;
        }else {
            currentChildData = parentList[index].expenseSummaryDetailDtos;
        }
        this.setState({currentChildData,currentIndex:index})
    }

    getSelectedDataFunc = (selectedList,record,index,newData) => {
        sessionStorage.setItem("childSelectList",JSON.stringify(selectedList));
    }

    freshData = (pageIndex) => {
        let {origalData} = this.props;
        let param = {
            page:pageIndex-1,
            size:origalData.size || 10
        }
        this.onPageSelect(param);
    }

    /**
     *
     * @param {*} index 跳转指定页数
     * @param {*} value 设置一页数据条数
     */
    onDataNumSelect = (index, value) => {
        let {origalData} = this.props;
        let param = {
            page:origalData.number || 0,
            size:value
        }
        this.onPageSelect(param);
    }

    /**
     *
     * @param {Number} value  pageIndex 或者 pageIndex
     * @param {Number} type 为0标识为 pageIndex,为1标识 pageSize
     */
    onPageSelect = (param) => {
        let {searchForm} = this.state;
        let {openGetDealModal,openFlag} = this.props;
        let params = {};
        searchForm = Object.assign({}, searchForm, param);
        params.param = searchForm;
        let searchField;
        if(openFlag == "ActivityProgram") {
            searchField = searchField1;
        }else {
            searchField = searchField2;
        }
        params.searchField = searchField
        openGetDealModal(openFlag,params);
    }

    renderFunc = (flag) => {
        let {queryParam,selectDataList={},openFlag} = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let dom = [];
        let childRowData = {};
        let self = this;
        let childType = "DataHeader";
        let required,searchField;
        if(openFlag == "ActivityProgram") {
            searchField = searchField1;
        }else {
            searchField = searchField2;
        }
        searchField.forEach((item,index) => {
            required = item.required;
            if(flag == 1 && index>2) {
                return false;
            }
            if(flag == 2 && index<3) {
                return true;
            }
            switch(item.type) {
                case 'FormControl':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                required={item.required}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                label={item.zhname}
                            >
                                <FormControl 
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                    {...getFieldProps(`${item.enname}`,{
                                        initialValue: childRowData[item.enname] || "",
                                        rules: [{
                                            required: required, message: "请输入",
                                        }],
                                    })}
                                />
                        </FormItem>);
                        break;
                case 'InputNumber':
                    dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <InputNumber toThousands={true}  
                                    key={`${item.enname}${index}`}
                                    iconStyle="one" step={1} disabled={!item.edit}
                                    {...getFieldProps(`${item.enname}`, {
                                        initialValue: (typeof childRowData[item.enname]) === "number" ? childRowData[item.enname] : 0,
                                        rules: [{
                                            required: required, message: "请输入",
                                        }],
                                    })}
                                />
                    </FormItem>);
                            break;
                case 'DatePicker':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <DatePicker 
                                    key={`${item.enname}${index}`}
                                    format={item.format || format} disabled={!item.edit}
                                    {...getFieldProps(`${item.enname}`, {
                                        // initialValue: childRowData[item.enname] && moment(childRowData[item.enname]) || moment(),
                                        validateTrigger: 'onBlur',
                                        rules: [{ 
                                            required: required, 
                                            message: '请选择',
                                         }],
                                    })}
                                />
                        </FormItem>);
                            break;
                case 'RangePicker':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <RangePicker 
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                    format={item.format}
                                    {...getFieldProps(`${item.enname}`, {
                                        initialValue:[moment(),moment()],
                                        validateTrigger: 'onBlur',
                                        rules: [{ required: required, message: '请选择', }],
                                    })}
                                />
                        </FormItem>);
                            break;
                case 'RefComponent':
                        dom.push(<FormItem
                                className="time"
                                key={item.enname}
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <RefComponent
                                    key={`${item.enname}${index}`}
                                    constparam = {item.param}
                                    multiple={item.multiple || false}
                                    aliasparam = {self.state.refStateParam}
                                    aliasfieldName={item.alias}
                                    title={item.zhname}
                                    refName={item.refname}
                                    childType = {childType}
                                    fieldName={item.enname}
                                    clearMatchData={this.clearMatch}
                                    rules={[
                                        { 
                                            required: required, 
                                            message: '请选择',
                                            pattern: item.required && /[^{"refname":"","refpk":"","refcode":""}|{"refpk":"","refname":"","refcode":""}]/
                                        }
                                    ]}
                                    initialValue={childRowData[item.enname] || initValueString(childRowData[item.showname],childRowData[item.enname],item.required)}
                                    refTableOnClickSave={(refName, fieldName, data) => {
                                        if(item.offers) {
                                            self.resetOfferRef(item,childType,childRowData);
                                        }
                                        if(item.cascadeName) {
                                            //item 配置数据
                                            //data 参照返回数据
                                            //fieldName 参照Id字段
                                            //childType 字表所属字段
                                            self.calcuParm(item,data,fieldName,childType);
                                        }
                                    }}
                                    form={self.props.form}
                                />
                        </FormItem>);
                            break;
                case 'Select':
                        let options = selectDataList[item.code] || item.options;
                        dom.push(<FormItem
                                className="time"
                                FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                required={item.required}
                                label={item.zhname}
                            >
                                <Select
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                    {
                                    ...getFieldProps(`${item.enname}`, {
                                        initialValue: childRowData[item.enname] || "",
                                        rules: [{ 
                                            required: required, 
                                            message: '请选择',
                                         }],
                                    })
                                    }
                                >
                                    <Option value="">请选择</Option>
                                    {
                                        options && options.map((item, index) => {
                                            return (
                                                <Option key={index} value={item.code}>{item.name}</Option>
                                            )
                                        })
                                    }
                                    
                                </Select>
                        </FormItem>);
                            break;
                    case 'Radio':
                            dom.push(<FormItem
                                    key={item.enname}
                                    required={item.required}
                                    FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                                    label={item.zhname}
                                >
                                    <Radio.RadioGroup
                                    key={`${item.enname}${index}`}
                                    disabled={!item.edit}
                                        {
                                        ...getFieldProps(`${item.enname}`, {
                                            initialValue: childRowData[item.enname] || '1',
                                            rules: [{ 
                                                required: required, 
                                                message: '请选择',
                                             }],
                                        }
                                        ) }
                                    >
                                         {
                                            item.options && item.options.map((itemoption, index) => {
                                                return (
                                                    <Radio 
                                                    disabled={!item.edit}
                                                    key={index} value={itemoption.key}>{itemoption.value}</Radio>
                                                )
                                            })
                                        }
                                    </Radio.RadioGroup>
                            </FormItem>);
                                break;
                    default: break;
            }
        })
        return dom;
    }



    render() {
        let {onCallback,showGetDealModal,parentList=[],form,origalData,openFlag} = this.props;
        let { getFieldProps, getFieldError } = this.props.form;
        let {number,size,totalPages,totalElements} = origalData
        let {currentChildData} = this.state;
        let {createDate,billCode,promoter
        } = this.state.searchObj || {}
        let self = this;
        let paginationObj = {   // 分页
            activePage: number+1,//当前页
            total: totalElements,//总条数
            size:size,
            items: totalPages,
            onSelect: this.freshData,
            onDataNumSelect: this.onDataNumSelect,
        }

        let columns,columnsChild;
        if(openFlag=="ActivityProgram"){
            columns = columns1;
            columnsChild = columns1Child;
        }else {
            columns = columns2;
            columnsChild = columns2Child;
        } 

        let headchildren = <FormList size="sm">
                            {self.renderFunc(1)}
                        </FormList> 
        return (
            <Modal
            show={showGetDealModal}
            size={'xlg'}
            className="getdeal"
            onHide={() => this.GetDealModal(false)} >
            <Modal.Header closeButton>
                <Modal.Title>拉单</Modal.Title>
            </Modal.Header>

            <Modal.Body>
                <SearchPanel
                    form={form}
                    reset={this.reset}
                    onCallback={onCallback}
                    intl={this.props.intl}
                    search={this.search}
                    headchildren={headchildren}>
                    <FormList size="sm">
                    {self.renderFunc(2)}
                    </FormList> 
                </SearchPanel>  
                <Table
                    className="expanded-table"
                    columns={columns}
                    onRowClick = {this.onParentRowClick}
                    data={parentList}
                />
                <div className="center"><Pagination
                    prev
                    next
                    maxButtons={5}
                    boundaryLinks
                    showJump={true}
                    {...paginationObj}
                /></div>
                <h3>明细</h3>
                <MultiSelectTable
                    className="expanded-table"
                    columns={columnsChild}
                    getSelectedDataFunc = {this.getSelectedDataFunc}
                    data={currentChildData || []}
                />
               
            </Modal.Body>

            <Modal.Footer>
                <Button onClick={() => this.GetDealModal(false)} style={{ marginRight: 10 }}><FormattedMessage id="js.Ref.Ref224.0012" defaultMessage="关闭" /></Button>
                <Button onClick={() => this.GetDealModal(true)} ><FormattedMessage id="js.com.Pas.0005" defaultMessage="确定" /></Button>
            </Modal.Footer>
        </Modal>

        )
    }
}

export default FormList.createForm()(injectIntl(GetDealModal))
